<?php
/***/
namespace app\admin\controller;

use app\admin\model\Channel;
use think\facade\Config;

/**
 * 充值管理
 * @Author    lf
 * @DateTime  2018-06-20T09:40:52+0800
 */
class Recharge extends Father {
	public function __construct() {
		//一定要先执行父类控制器
		parent::__construct();

		if (session('user_type') != 'admin') {

			echo "~该页面没有权限！";exit;
		}
	}

	/**
	 * 首页
	 * @Author   lf
	 * @DateTime 2018-06-28T16:03:18+0800
	 * @return   [type]                   [description]
	 */
	public function index($page = 1) {
		//总的
		$field_list = [
			['field' => 'numbers', 'type' => 'numbers', 'title' => '序号']
			, ['field' => 'channel_id', 'title' => '渠道ID']
			, ['field' => 'company_name', 'title' => '渠道名', 'minWidth' => 150]
			, ['field' => 'user_name', 'title' => '联系人', 'minWidth' => 120]
			, ['field' => 'channel_phone', 'title' => '联系电话', 'minWidth' => 120]
			, ['field' => 'overdraft_limit', 'title' => '透支额度', 'minWidth' => 120]
			, ['field' => 'oevrplus', 'title' => '账户余额(元)', 'minWidth' => 120]
			, ['field' => 'balance', 'title' => '短信余额(条)', 'minWidth' => 120]
			, ['field' => 'status_', 'title' => '渠道状态', 'minWidth' => 100, 'align' => 'center']
			, ['field' => 'right', 'fixed' => 'right', 'title' => '操作', 'toolbar' => '#barDemo', 'width' => 110, 'unresize' => 'true'],
		];
		if (session('username') != 'admin') {
			//总的列
			$field_list_column = array_column($field_list, 'field');
			//可用的列
			$table_list = db('adm_role_table_list')->join("adm_table_list", "adm_role_table_list.table_field_id=adm_table_list.id")->where('role_id', session('role_id'))->where('adm_table_list.auth_id', 49)->column('adm_table_list.table_field');

			foreach ($field_list_column as $key => $value) {
				//隐藏列
				if (!in_array($value, $table_list)) {
					unset($field_list[$key]);
				}
			}
		}

		if (input('get.api')) {

			$request = input('get.');
			$cha     = isset($request['cha']) ? trim($request['cha']) : '';
			$where   = [];

			if ($cha) {

				$where['channel_id'] = $cha;
			}

			//实例化
			$channelm = new Channel();
			//分页查询
			$data = $channelm->withSearch(['off_redis'])
				->field('level,channel_id,company_name,user_name,channel_phone,overdraft_limit,oevrplus,sms_price,status')
			// ->field(array_filter(array_column($field_list,'field')))
			// ->field(['channel_id'])
				->where($where)
			// ->where('level','in',[1,4])
				->paginate($request['limit'])
				->each(function ($item, $index) {

					if (isset($item->status)) {
						switch ($item->status) {

						case '0':
							$item->status_ = '<span class="layui-badge">冻结</span>';
							break;
						case '1':
							$item->status_ = '<span class="layui-badge layui-bg-green">活跃</span>';
							break;

						default:
							break;
						}
					}

					//换算短信条数
					if (isset($item->sms_price) && $item->sms_price > 0) {

						$item->balance = floor($item->oevrplus / $item->sms_price);
					} else {

						$item->balance = 0;
					}

				});

			$count = $data->total();

			$list = $data->toArray();

			$list = $list['data'];

			return json(['code' => 0, 'msg' => '', 'count' => $count, 'data' => $list]);

		} else {
			$this->assign('field_list', json_encode($field_list));
			$this->assign('channels', Channel::withSearch(['off_redis'])->field('channel_id,company_name')->select());

			return $this->fetch();

		}
	}

	/**
	 * 充值
	 * @Author   lf
	 * @DateTime 2018-06-28T16:03:00+0800
	 * @return   [type]                   [description]
	 */
	public function recharge_add() {

		if (session('username') == 'admin2018') {

			$this->admin_add();
			return $this->fetch('admin2018_add');exit;
		}

		if (session('user_type') != 'admin') {
			return;
		}

		if ($_SERVER['REQUEST_METHOD'] == 'POST') {

			$channel_id  = trim(input('post.channel_id'));
			$rechargenum = sprintf('%.3f', trim(input('post.rechargenum')));
			$remarks     = trim(input('post.remarks'));

			$validate = validate('Channel');
			if (!$validate->scene('rec_add')->check(['channel_id1' => $channel_id, 'rechargenum' => $rechargenum])) {

				echo $validate->getError();return;
			}
			//实例化
			$channelm = new Channel();
			$channelm->setSmsBalance($channel_id, $rechargenum, $remarks);
			return;
		}

		$channel_id       = trim(input('get.channel_id'));
		$channel          = Channel::get(['channel_id' => $channel_id]);
		$channel->balance = floor($channel->oevrplus / $channel->sms_price);

		$this->assign('mode', $channel);

		return $this->fetch();
	}

	/**
	 * 调价
	 * @Author   lf
	 * @DateTime 2018-06-29T15:55:14+0800
	 * @return   [type]                   [description]
	 */
	public function recharge_adjust() {

		if (session('user_type') != 'admin') {

			return;
		}

		if ($_SERVER['REQUEST_METHOD'] == 'POST') {

			$channel_id = trim(input('post.channel_id'));
			$newprice   = sprintf('%.3f', trim(input('post.newprice')));
			$remarks    = trim(input('post.remarks'));

			$validate = validate('Channel');
			if (!$validate->scene('rec_adjust')->check(['channel_id' => $channel_id, 'rechargenum' => $newprice])) {

				echo $validate->getError();return;
			}

			//实例化
			$channelm = new Channel();
			$channelm->adjustSmsBalance($channel_id, $newprice, $remarks);
			return;
		}

		$channel_id       = trim(input('get.channel_id'));
		$channel          = Channel::get(['channel_id' => $channel_id]);
		$channel->balance = floor($channel->oevrplus / $channel->sms_price);

		$this->assign('mode', $channel);
		return $this->fetch();
	}

	/**
	 * 余额转移
	 * @Author   lf
	 * @DateTime 2018-07-02T09:59:25+0800
	 * @return   [type]                   [description]
	 */
	public function recharge_shift() {
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$channel_id       = trim(input('post.channel_id'));
			$channel_id_shift = trim(input('post.channel_id_shift'));
			$num_shift        = trim(input('post.num_shift'));
			$remarks          = trim(input('post.remarks'));

			if ($channel_id == $channel_id_shift) {

				echo '不能转给自己';return;
			}

			if (empty($channel_id) || empty($channel_id_shift) || empty($num_shift)) {

				echo "不能为空值";return;
			}

			//实例化
			$channelm = new Channel();
			$channelm->shiftSmsBalance($channel_id, $channel_id_shift, $num_shift, $remarks);
			return;
		}

		$channel_id = trim(input('get.channel_id'));

		$channel_mode          = Channel::get(['channel_id' => $channel_id]);
		$channel_mode->balance = floor($channel_mode->oevrplus / $channel_mode->sms_price);

		$where = ['channel_id' => ['<>', $channel_id], 'sms_price' => $channel_mode['sms_price']];

		if (is_OneCha()) {
			$where['p_id']  = session('relate_id');
			$where['level'] = 2;
		}
		$channel_id_list = Channel::withSearch(['off_redis'])->where($where)->column('channel_id,company_name', 'id');

		$this->assign('mode', $channel_mode);
		$this->assign('channel_id_list', $channel_id_list);
		return $this->fetch();
	}

	/**
	 * 退款
	 * @Author   lf
	 * @DateTime 2018-07-03T14:39:57+0800
	 * @return   [type]                   [description]
	 */
	public function recharge_refund() {
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$channel_id = trim(input('post.channel_id'));
			$refundnum  = sprintf('%.3f', trim(input('post.refundnum')));
			$remarks    = trim(input('post.remarks'));

			$validate = validate('Channel');
			if (!$validate->scene('rec_add')->check(['channel_id1' => $channel_id, 'rechargenum' => $refundnum])) {
				echo $validate->getError();
				return;
			}
			//实例化
			$channelm = new Channel();
			$channelm->setBalanceRefund($channel_id, $refundnum, $remarks);
			return;
		}

		$channel_id       = trim(input('get.channel_id'));
		$channel          = Channel::get(['channel_id' => $channel_id]);
		$channel->balance = floor($channel->oevrplus / $channel->sms_price);

		$this->assign('mode', $channel);
		return $this->fetch();
	}

	/**
	 * redis清款
	 * @Author   lf
	 * @DateTime 2019-08-09T15:28:09+0800
	 * @return   [type]                   [description]
	 */
	public function clearRedisMoney() {
		$cid = input('post.cid');

		if ($cid > 0) {
			$config = Config::get('ZD_REDIS_CONFIG');

			$redis = redisCurl($config['IP'], $config['PORT'], $config['PASSWORD'], 4);

			$price_cid = $redis->get('PRICE_CID_' . $cid);

			trace(session("username") . "进行清款操作，原值：" . $price_cid . "；操作渠道：" . $cid, "log");

			if ($price_cid == false) {
				return json(['code' => 1]);
			}

			return json(['code' => $redis->del('PRICE_CID_' . $cid)]);
		}

		return json(['code' => 0]);
	}

//

}
